<?php
/**
* 手机web菜单管理类
*/
class mc_mobile_menu extends ms_base
{
	protected $menus = array();

	public function __construct()
	{
		parent::__construct();
		$this->load();
	}

	public function load()
	{
		if($this->menus) return $this->menus;
		$menus = S('mobile:menus');
		if($menus) {
			$menus = ms_mxml::to_array($menus);
			if(is_array($menus) && $menus) {
				$this->menus = $menus;
				return $this->menus;
			}			
		}
		return false;
	}

	public function save($menus)
	{
		static $fields = array('title', 'url', 'iconurl', 'flag');

		if($menus)foreach ($menus as $key => $value) {
			foreach ($value as $_key => $_value) {
				//删除未定义的字段
				if(!in_array($_key, $fields)) {
					unset($value[$_key]);
					continue;
				}
				$value[$_key] = _T($_value);
				if(!$value[$_key] && $_key!='flag') return $this->add_error('对不起，表单项不能为空（标题，链接和图片）。');
			}
			if(strposex($value['iconurl'], '/temp/')) {
				$iconurl = $this->move_local_picture($value['iconurl']);
				$menus[$key]['iconurl'] = $iconurl?$iconurl:'';
			}
		}

		//转换成XML保存
		$menus_str = $menus ? ms_mxml::from_array($menus) : '';

		$cfg_mdl = _G('loader')->model('config');
		$result = $cfg_mdl->save_one('menus', $menus_str, 'mobile');
		if(!$result) return;

		if($this->menus) foreach ($this->menus as $key => $value) {
			$del = true;
			if($menus) foreach ($menus as $k => $v) {
				if($v['iconurl'] == $value['iconurl']) $del=false; //新旧对比，如果新提交不存在的，就进行删除
			}
			if($del) {
				$this->delete_image($value['iconurl']);
			}
		}
	}

	public function reset()
	{
		$links = _G('hook')->hook('mobile_index_link', null, true);
		if(!$links) return false;
		$menus = array();
		foreach ($links as $links) {
			$links['iconurl'] = 'templates/mobile/default/images/menu/'.$links['icon'].'.png';
			unset($links['icon']);
			$menus[] = $links;
		}
		$this->save($menus);
		return $menus;
	}


	//把上传临时文件夹的图片移动到正式保存文件夹
	protected function move_local_picture($pic)
	{
		$sorcuefile = MUDDER_ROOT . $pic;
		if(!is_file($sorcuefile)) {
			return false;
		}
		if(function_exists('getimagesize') && !@getimagesize($sorcuefile)) {
			@unlink($sorcuefile);
			return false;
		}

		$IMG = new ms_image();
		$IMG->thumb_mod = S('picture_createthumb_mod');

		$path = 'uploads';
		$name = basename($sorcuefile);
		$subdir = 'mobile'.DS.'menus';
		$dirs = explode(DS, $subdir);

		foreach ($dirs as $val) {
			$path .= DS . $val;
			if(!@is_dir(MUDDER_ROOT . $path)) {
				if(!mkdir(MUDDER_ROOT . $path, 0777)) {
					show_error(lang('global_mkdir_no_access',$path));
				}
			}
		}
		$result = array();
		$filename = $path . DS . $name;
		$picture = str_replace(DS, '/', $filename);
		if(!copy($sorcuefile, MUDDER_ROOT . $filename)) {
			return false;
		}

		if(!DEBUG) @unlink($sorcuefile);
		return $picture;
	}

	protected function delete_image($pic)
	{
		if(strlen($pic) > 10 && !strposex($pic, 'templates/')) {
			return @unlink(MUDDER_ROOT.$pic);
		}
		return false;
	}
}
/** end */